package com.newy.service.sys;

import java.util.Date;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.newy.core.BaseService;
import com.newy.core.util.Page;
import com.newy.core.web.AppContext;
import com.newy.dao.sys.LoginLogDao;
import com.newy.domain.sys.LoginLog;
import com.newy.domain.sys.LoginLog.LogoutType;
import com.newy.domain.sys.User;

/**
 * 日志管理服务类
 * @author linzongxue
 *
 */
@Service
@Transactional
public class LogService  extends BaseService{
	private @Resource LoginLogDao loginLogDao;
	private @Resource UserService userMgr;
	
	/**
	 * 添加当前登陆用户的登陆日志
	 * @param userId 当前用户ID
	 */
	public LoginLog addCurrentLoginLog(Long userId){
		LoginLog log = new LoginLog();
		log.setUserId(userId);
		log.setLoginTime(new Date());
		log.setIpAddress(AppContext.getRequest().getRemoteAddr());
		log.setBrowser(getBrowser(AppContext.getRequest().getHeader("user-agent")));
		log.setSessionId(AppContext.getRequest().getRequestedSessionId());
		loginLogDao.save(log);
		return log;
	}
	
	/**
	 * 更新登陆日志的退出类型和退出时间
	 * @param sessionId 会话ID
	 * @param logoutType
	 */
	public void updateLoginTypeAndTime(String sessionId, LogoutType logoutType){
		LoginLog log = loginLogDao.findUniqueBy("sessionId", sessionId);
		if (log != null){
			log.setLogoutTime(new Date());
			log.setLogoutType(logoutType);
			loginLogDao.save(log);
		}
	}
	
	/**
	 * 检查意外退出的情况，并更新数据。
	 * 此方法应在系统启动时调用。
	 */
	public void checkUnexceptedLogout(){
		for (LoginLog log : loginLogDao.findBy("logoutType", null)){
			log.setLogoutType(LogoutType.UNEXPECTED);
		}
	}
	
	public void deleteLoginLog(Long id){
		loginLogDao.delete(id);
	}
	
	public void deleteLoginLogs(Long[] ids){
		loginLogDao.deleteMulti(ids);
	}
	
	public Page findLoginLogsByPage(Page page, LoginLog loginLog){
		return loginLogDao.findPageByExample(page, loginLog, "loginTime", false);
	}

	public User getUserOfLoginLog(LoginLog log){
		return userMgr.getUser(log.getUserId());
	}
	
	/**
	 * 通过user-agent猜测各种浏览器类型，猜不出则返回user-agent
	 */
	private String getBrowser(String userAgent){
		String lowerAgent = userAgent.toLowerCase();
		String[] temp = null;
		try{
			if (lowerAgent.contains("opera")){ //听闻是最标准的user-agent
				return "Opera " + lowerAgent.substring(lowerAgent.lastIndexOf('/') + 1);
			}
			else if (lowerAgent.contains("chrome")){ //它含有safari
				temp = userAgent.split(" ");
				return temp[temp.length - 2].trim().replace("/", " ");
			}
			else if (lowerAgent.contains("safari")){
				temp = userAgent.split(" ");
				return "Safari " + temp[temp.length - 2].split("/")[1];
			}
			else if (lowerAgent.contains("msie")){
				return userAgent.split(";")[1].trim();
			}
			else if (lowerAgent.contains("firefox")){
				return "Firefox " + userAgent.substring(userAgent.lastIndexOf('/') + 1).trim();
			}
		}
		catch(Exception e){
			
		}
		return userAgent.length() > 200 ? userAgent.substring(0, 200) : userAgent;
	}
}
